#include "pagecontrol.h"

#include "lualib.h"
#include "lua.h"
#include "lauxlib.h"

#include <string.h>
#include <stdio.h>
#include <memory.h>
#include <stdlib.h>

extern lua_State* g_ufo_lua_state;

static int lua_ufoPageControlSetCurrentPage(lua_State *L)
{
	UFO_View view = *(UFO_View*)luaL_checkudata(L, 1, "ufo.ufoView");
	int nIndex = lua_tonumber(L, 2);
	lua_pushinteger(L, ufoPageControlSetCurrentPage(view, nIndex));
	return 1;
}

static int lua_ufoPageControlSetNumberOfPages(lua_State *L)
{
	UFO_View view = *(UFO_View*)luaL_checkudata(L, 1, "ufo.ufoView");
	int numberOfPages = lua_tonumber(L, 2);
	lua_pushinteger(L, ufoPageControlSetNumberOfPages(view, numberOfPages));
	return 1;
}

static int lua_ufoPageControlSetImage(lua_State *L)
{
	UFO_View view = *(UFO_View*)luaL_checkudata(L, 1, "ufo.ufoView");

	int nIndex = lua_tonumber(L, 2);

	const char *texNormal = lua_tostring(L, 3);
	UFO_Texture normal = ufoResourceGetTexture(texNormal);

	const char *texHighlight = lua_tostring(L, 4);
	UFO_Texture highlight = ufoResourceGetTexture(texHighlight);

	lua_pushinteger(L, ufoPageControlSetImage(view, nIndex, normal, highlight));

	return 1;
}

static const struct luaL_Reg pagecontrollib [] = {
	{"setCurrentPage", lua_ufoPageControlSetCurrentPage},
	{"setNumberOfPages", lua_ufoPageControlSetNumberOfPages},
	{"setImage", lua_ufoPageControlSetImage},
	{0, 0},
};

int internal_initializationScript_pagecontrol()
{
	if (!g_ufo_lua_state) {
		g_ufo_lua_state = luaL_newstate();
		luaL_openlibs(g_ufo_lua_state);
	}

	luaL_newmetatable(g_ufo_lua_state, "ufo.ufoView");

	lua_pushvalue(g_ufo_lua_state, -1);
	lua_setfield(g_ufo_lua_state, -2, "__index");

	luaL_register(g_ufo_lua_state, 0, pagecontrollib);

	return 1;
}